import axios, { AxiosError, AxiosProxyConfig, AxiosInstance, AxiosResponse } from "axios";
import { Platform } from 'react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { BASE_URL } from "../config";



const instance = axios.create({
    baseURL: Platform.select({
        android: BASE_URL,
        ios: BASE_URL
    }),
    headers: {
        'Content-Type': 'application/json',
    },
    timeout: 30000,
})

// 请求拦截器
instance.interceptors.request.use(async config => {
    // 发请求是自动带上token
    const token = await AsyncStorage.getItem('token')
    if (token) {
        config.headers.Authorization = `Bearer ${token}`
    }

    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截器
instance.interceptors.response.use(response => {
    return response.data
}, error => {
    Promise.reject(error)
})

// 定义返回接口类型
interface ApiResponse<T = any> {
    code: number,
    data: T,
    message: string,
    timestamp: number
}

const api = {
    get: <T>(url: string, params?: any, config?: AxiosProxyConfig): Promise<ApiResponse<T>> => {
        return instance.get(url, { params, ...config, validateStatus: () => true })
    },
    post: <T>(url: string, data?: any, config?: AxiosProxyConfig): Promise<ApiResponse<T>> => {
        return instance.post(url, data, { ...config, validateStatus: () => true })
    },
    postFile: <T>(url: string, formData: FormData, config?: AxiosProxyConfig): Promise<ApiResponse<T>> => {
        return instance.post(url, formData, {
            ...config, headers: {
                'Content-Type': 'multipart/form-data', // 必须设置正确的 Content-Type
            }, validateStatus: () => true
        })

    },
    put: <T>(url: string, data?: any, config?: AxiosProxyConfig): Promise<ApiResponse<T>> => {
        return instance.put(url, data, { ...config, validateStatus: () => true })
    },
    delete: <T>(url: string, data?: any, config?: AxiosProxyConfig): Promise<ApiResponse<T>> => {
        return instance.delete(url, { data, ...config, validateStatus: () => true })
    }

}

export default api